<?php
/**
 * Created by PhpStorm.
 * User: yunpeng
 * Date: 2018/12/28
 * Time: 13:46
 */

namespace App\Admin\Controllers;

use App\Models\User;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Facades\Admin;
use App\Imports\UsersImport;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use PhpOffice\PhpSpreadsheet\Exception;


class UsersController extends Controller
{
    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        return $content
            ->header('用户列表')
            ->body($this->grid());
    }



    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {
            $content->header('创建用户');
            $content->body($this->form());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {
            $content->header('编辑用户');
            $content->body($this->form()->edit($id));
        });
    }

    public function import()
    {
        try {
            Excel::import(new UsersImport, request()->file('file'));
         } catch (Exception $e){
            echo $e->getMessage();
        }

        return redirect()->back()->with('status', 'Profile updated!');;
    }



    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

        $grid = new Grid(new User);

        $grid->filter(function($filter){

            // 去掉默认的id过滤器
            $filter->disableIdFilter();

            // 在这里添加字段过滤器
            $filter->like('name', '名称');
            $filter->like('phone', '手机号');
            $filter->like('grade', '等级');
            $filter->equal('distribution_invite_code', '分佣邀请码');
            $filter->equal('commission_invite_code', '分佣邀请码');
            $filter->equal('status','状态')->radio([
                ''   => '全部',
                0    => '注册未通过',
                1    => '注册通过',
            ]);


        });

        $grid->id('Id');
        $grid->name('名称');
        $grid->img('头像')->image(env('APP_URL')."/storage",50,50);
        $grid->phone('手机号');
        $grid->iden('身份证号');
        $grid->grade('等级');
        $grid->recharge('充值金额');
        $grid->reward('奖励金额');
        $grid->distribution_invite_code('分佣邀请码');
        $grid->commission_invite_code('分销邀请码');

        $states = [
            'on'  => ['value' => 'on', 'text' => '通过', 'color' => 'primary'],
            'off' => ['value' => 'off', 'text' => '不通过', 'color' => 'default'],
        ];
        $grid->status('注册审核')->switch($states);

        $transfer_status = [
            'on'  => ['value' => 'on', 'text' => '通过', 'color' => 'primary'],
            'off' => ['value' => 'off', 'text' => '不通过', 'color' => 'default'],
        ];
        $grid->transfer_status('积分转让审核')->switch($transfer_status);
        $grid->created_at('创建时间');
        $grid->updated_at('修改时间');
        $grid->disableExport();
        //禁用批量删除按钮
        $grid->tools(function ($tools) {
            $tools->batch(function ($batch) {
                $batch->disableDelete();
            });
        });
        $grid->tools(function ($tools) {
            $tools->append(new \App\Admin\Extensions\Tools\Excel());
        });
        $grid->actions(function ($actions) {
        // prepend一个操作
        $actions->prepend("<a href='/admin/users/downline/".$actions->getKey()."'><i class='fa fa-user-o'></i></a>");
        $actions->prepend("<a href='/admin/orders/".$actions->getKey()."'><i class='fa fa-file-text-o'></i></a>");
        $actions->disableView();
        $actions->disableDelete();
    });
        //$grid->disableCreateButton();

        return $grid;
    }



    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function downlinegrid($id)
    {
        $grid = new Grid(new User);
        // 添加默认查询条件
        $grid->model()->where('commission_invite_code', $id);
        $grid->id('Id');
        $grid->name('名称');
        $grid->img('头像')->image(env('APP_URL')."/storage",50,50);
        $grid->password('密码');
        $grid->phone('手机号');
        $grid->iden('身份证号');
        $grid->grade('等级');
        $grid->recharge('充值金额');
        $grid->reward('奖励金额');
        $grid->distribution_invite_code('分佣邀请码');
        $grid->commission_invite_code('分销邀请码');
        $grid->status('状态');
        //$grid->remember_token('Remember token');
        $grid->created_at('创建时间');
        $grid->updated_at('修改时间');
        $grid->actions(function ($actions) {
            // prepend一个操作
            $actions->prepend("<a href='/admin/users/downline/".$actions->getKey()."'><i class='fa fa-user-o'></i></a>");
        });
        $grid->disableCreateButton();

        return $grid;
    }


    protected function downline(Content $content,$id)
    {
        return $content
            ->header('会员下线')
            ->body($this->downlinegrid($id));

    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        // 创建一个表单
        return Admin::form(User::class, function (Form $form) {

            $form->text('name','名称');
            // 创建一个选择图片的框
            $form->image('img', '头像');
            $form->password('password','密码')->default('**********')->rules('nullable|required');
            $form->text('phone','手机号');
            $form->text('iden','身份证号');
            $form->text('grade','等级');
            $form->text('recharge','充值金额');
            $form->text('reward','奖励金额');
            $form->text('sale','销售金额');
            $form->text('distribution_invite_code','分佣邀请码');
            $form->text('commission_invite_code','分销邀请码');
            $form->radio('status', '注册审核')->options(['on' => '通过', 'off' => '不通过'])->default('off');
            $form->radio('transfer_status', '积分转让审核')->options(['on' => '通过', 'off' => '不通过'])->default('off');
            $form->saving(function (Form $form) {
                if ($form->password && $form->model()->password != $form->password) {
                    $form->password = bcrypt($form->password);
                }
            });
        });
    }

    // 定义下拉框搜索接口
    public function apiIndex(Request $request)
    {
        // 用户输入的值通过 q 参数获取
        $search = $request->input('q');
        $result = User::query()
            ->where('name', 'like', '%'.$search.'%')
            ->paginate();

        // 把查询出来的结果重新组装成 Laravel-Admin 需要的格式
        $result->setCollection($result->getCollection()->map(function (User $user) {
            return ['id' => $user->id, 'text' => $user->name];
        }));

        return $result;
    }


}